<?php

namespace app\admin\controller\mox\inherit\story;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;


/**
 * 木偶戏文化传承故事章节
 *
 * @icon fa fa-circle-o
 */
class Chapter extends Backend
{

    /**
     * Chapter模型对象
     * @var \app\admin\model\mox\inherit\story\Chapter
     */
    protected $model = null;
    protected $s_id = null;
    protected $story = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mox\inherit\story\Chapter;
        // $this->s_id = $this->request->param('s_id');
        // if (!$this->s_id) {
        //     $this->error('缺少参数s_id');
        // }
        $this->assign('s_id', $this->s_id);
        // $this->story = model('app\admin\model\mox\inherit\story\Info')->where('id', $this->s_id)->find();
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $s_id = $this->request->param('s_id');
        $this->assignconfig('s_id', $s_id);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user', 'story'])
                ->where('s_id', $s_id)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $s_id = $this->request->param('s_id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['content'] = strip_tags($params['content']);
                $content_num = preg_replace('/\s+/u', '', $params['content']);
                $params['content_num'] = mb_strlen($content_num, 'utf-8');
                $content = $params['content'];
                //删除数据库小说章节表不存在的字段
                unset($params['content']);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $params['s_id'] = $s_id;
                    $params['user_id'] = $this->auth->user_id;
                    $params['create_time'] = time();
                    $result = $this->model->validate(false)->save($params);
                    $row = $this->model
                        ->where('s_id',  $s_id)
                        ->where('user_id',  $this->auth->user_id)
                        ->where('create_time', $params['create_time'])
                        ->find();
                    $fileName = md5(md5($row['id']) .  $s_id);
                    $file_name = "public/uploads/mox_story/" .  $s_id . "/" . $fileName . ".txt";
                    $dirPath = "public/uploads/mox_story/" . $s_id;
                    $saveDir = $path = ROOT_PATH;
                    if (!file_exists($saveDir . $dirPath)) {

                        mkdir(ROOT_PATH . $dirPath, 0777, true);
                    }
                    $filePath =  $saveDir .  $file_name;
                    $file = file_put_contents($filePath, $content);
                    Db::commit();
                } catch (ValidateException $e) {

                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false && $file !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError() ?: __('No rows were inserted'));
                }
            } else {
                $this->error();
            }
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $s_id = $this->request->param('s_id');
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['content'] = strip_tags($params['content']);
                $content_num = preg_replace('/\s+/u', '', $params['content']);
                $params['content_num'] = mb_strlen($content_num, 'utf-8');
                $content = $params['content'];
                //删除数据库小说章节表不存在的字段
                unset($params['content']);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $params['user_id'] = $this->auth->user_id;
                    $params['update_time'] = time();
                    $result = $this->model->validate(false)->save($params, ['id' => $ids]);
                    $fileName = md5(md5($ids) . $s_id);
                    $file_name = "public/uploads/mox_story/" . $s_id . "/" . $fileName . ".txt";
                    $dirPath = "public/uploads/mox_story/" . $s_id;
                    $saveDir = $path = ROOT_PATH;
                    if (!file_exists($saveDir . $dirPath)) {

                        mkdir(ROOT_PATH . $dirPath, 0777, true);
                    }
                    $filePath =  $saveDir .  $file_name;
                    file_put_contents($filePath, $content);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback(); // 回滚事务
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback(); // 回滚事务
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback(); // 回滚事务
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError() ?: __('No rows were inserted'));
                }
            } else {
                $this->error();
            }
        }
        $fileName = md5(md5($ids) . $s_id);
        $file_name = "public/uploads/mox_story/" . $s_id . "/" . $fileName . ".txt";
        $saveDir = $path = ROOT_PATH;
        $filePath =  $saveDir .  $file_name;
        if (file_exists($filePath)) {
            $content = file_get_contents($filePath);
            $row['content'] = $content;
        } else {
            $row['content'] = '';
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function cxselect()
    {
        $s_id = $this->request->get('s_id');
        $list = Db::name('mox_inherit_story_chapter')->where('s_id', $s_id)->field('id as value, title as name')->select();
        $this->success('', '', $list);
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 获取文件夹路径
                    $saveDir = $path = ROOT_PATH;
                    $s_id = $v['s_id'];
                    $fileName = md5(md5($v['id']) .  $s_id);
                    $file_name = "public/uploads/mox_story/" .  $s_id . "/" . $fileName . ".txt";
                    // 删除章节
                    $result = model('app\admin\model\mox\inherit\story\Chapter')->where('id', $v['id'])->delete();
                    // 删除章节文件
                    unlink($saveDir .  $file_name);
                }
                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        return;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
